import React from 'react';
import {HashRouter as Router, Route, Switch, Redirect} from 'react-router-dom'
import App from './App'
import Login from './components/login'
import Admin from './admin'
import NoMatch from './components/nomatch'
import Routers from './routerMap'
import {connect} from 'react-redux';

class IRouter extends React.Component {
    render() {
        let token = this.props.token
        return (
            <Router>
                <App>
                    <Switch>
                        <Route path="/login" component={Login} />
                        <Route path="/dashboard"  render= {() => 
                            <Admin>
                                <Switch>
                                    {Routers.map((item, index) => {
                                        return <Route key={index} path={item.path} exact render={props =>
                                            (!item.auth ? (<item.component {...props} />) : (token ? <item.component {...props} /> : <Redirect to={{
                                            pathname: '/login',state: { from: props.location }}} />)
                                            )
                                            } />
                                    })}
                                    <Route component={NoMatch} />
                                </Switch>
                            </Admin>
                        } />
                        <Redirect from="/" to="/login" />
                        <Route component={NoMatch} />
                    </Switch>
                </App>
            </Router>
        );
    }
}

const mapStateToProps = (state) => {
    return { token: state.token }
}

export default connect(mapStateToProps)(IRouter);